require("babel-core/register");  //es7

// 初始化Client
var co = require('co');
var OSS = require('ali-oss');
var fs = require('fs');

var path = require('path')
var glob = require('glob');
var config = require('../config')

// var client = new OSS({
//     region: 'oss-cn-hongkong',
//     accessKeyId: 'LTAIxRhcyfiOMYDv',
//     accessKeySecret: 'dI4lELKjbvf1eP8WKePRFn4hQN5rKc'
// });
// var ali_oss = {
//     bucket: 'bcoin-hk',
//     endPoint: 'oss-cn-hongkong.aliyuncs.com'
// }

var client = new OSS({
    region: 'oss-cn-hongkong',
    accessKeyId: 'LTAIMXqJbWDMFCmm',
    accessKeySecret: 'uFBj8IcgkRNt7QFDGTZUDSD5935gaI'
});
var ali_oss = {
    bucket: 'bcoin-hk',
    endPoint: 'oss-cn-hongkong.aliyuncs.com'
}


// glob.sync('./dist/').forEach(function (entry) {
//     console.log(entry)
// });

var distPath = path.resolve(__dirname, '../dist/static')

//遍历读取文件 
var filesList = [];
function readFile(path, filesList) {
    var files = fs.readdirSync(path);//需要用到同步读取 
    files.forEach(walk);
    function walk(file) {
        var states = fs.statSync(path + '/' + file);
        if (states.isDirectory()) {
            readFile(path + '/' + file, filesList);
        }
        else {
            //创建一个对象保存信息 
            var obj = new Object();
            obj.size = states.size;//文件大小，以字节为单位 
            obj.name = file;//文件名 
            obj.path = path + '/' + file; //文件绝对路径 
            filesList.push(obj);
        }
    }
}
readFile(distPath, filesList);


function uploadToOss(filesList){
     // 阿里云 上传文件 
    co(function* () {
        client.useBucket(ali_oss.bucket);

        for (var i = 0; i < filesList.length; i ++){
            var file = filesList[i];
            var filePath = config.build.cdnHostPath + file.path.split('/dist/')[1];
            // console.log(filePath, file.path, "!!!!!")
            yield client.put(filePath, file.path);

            var str =  "文件名:" + file.name + " " + 
                        "大小:" + (file.size / 1024).toFixed(2) + "/kb" + " " + 
                        "路径:" + file.path + " 上传成功！" + "\n";
            console.log(str);
        }


    }).catch(function (err) {

        console.log(JSON.stringify(err));

        throw new Error(err)
    });
}

uploadToOss(filesList);


